import { ref } from 'vue'
import { useRoute,onBeforeRouteUpdate,useRouter } from 'vue-router'
import { useCookies } from '@vueuse/integrations/useCookies'

export function useTabList(){
    const route = useRoute()
    const router = useRouter()
    const cookie = useCookies()

    const activeTab = ref(route.path)
    const tabList = ref([
    {
        title: '后台首页',
        path: '/'
    }
    ])

    // 添加标签页方法
    function addTab(tab){
        let notTab = tabList.value.findIndex(t => t.path === tab.path) == -1
        if(notTab){
            tabList.value.push(tab)
        }
        // 添加到cookies
        cookie.set('tabList',tabList.value, {expires: new Date(Date.now() + 7 * 24 * 3600 * 1000)})
    }

    // 初始化导航标签列表
    function initTabList(){ 
        let tabs = cookie.get('tabList')
        if(tabs){
            tabList.value = tabs
        }
    }

    initTabList()

    // 路由监听
    onBeforeRouteUpdate((to,from) => {
        // 修改激活状态
        activeTab.value = to.path
        // 添加标签页
        addTab({
            title: to.meta.title,
            path: to.path
        })
    })

    // 标签改变
    const changeTab = (t) => {
        // 切换激活状态和路由
        router.push(t)
    }

    // 下拉框选中事件
    const handleClose = (e) => {
        // 处理关闭其他标签页
        if(e == 'closeOther'){
            tabList.value = tabList.value.filter(tab => tab.path == '/' || tab.path == activeTab.value)
        }
        // 处理关闭所有标签页
        else if(e == 'closeAll'){
            // 重新赋值并跳转路由
            tabList.value = [{
                title: '后台首页',
                path: '/'
            }]
            router.push('/')
        }
        // 存储新的值到cookie之中
        cookie.set('tabList',tabList.value, {expires: new Date(Date.now() + 7 * 24 * 3600 * 1000)})
    }

    const removeTab = (t) => {
        // 获取当前标签列表和激活的标签
        let tabs = tabList.value
        let active = activeTab.value
        // 判断当前删除标签页是否为激活的标签
        if(active == t){
            // 遍历标签列表,去寻找当前删除标签的后一条或者前一条
            tabs.forEach((tab,index) => {
                if(tab.path == t){
                    // 或者当前需要激活的索引
                    const newTab = tabs[index + 1] || tabs[index - 1]
                    if(newTab){
                        // 赋值tab值
                        active = newTab.path
                    }
                }
            })
        }
        // 更新tabs列表
        tabList.value = tabs.filter(tab => tab.path != t)
        // 更新cookies值
        cookie.set('tabList',tabList.value, {expires: new Date(Date.now() + 7 * 24 * 3600 * 1000)})
        // 路由更新 
        router.push(active)
    }
    return {
        activeTab,
        tabList,
        changeTab,
        handleClose,
        removeTab
    }
}
